package com.zzx.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: Spider Man
 * @Description: servlet，发送请求到HandlerMapping和接收数据返回给客户端
 * @Date Created in 2020-09-10 17:01
 * @Modified By:
 */
public class DispatcherServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        InputStream resourceAsStream = DispatcherServlet.class.getClassLoader().getResourceAsStream("application.properties");
        HandlerMapping.load(resourceAsStream);
        try {
            assert resourceAsStream != null;
            resourceAsStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        //通过请求的uri键获取map中对应的值信息
        HandlerMapping.MVCMapping mvcMappingInfo = HandlerMapping.getMVCMappingInfo(uri);

        if (mvcMappingInfo == null){
            resp.sendError(404,"请求地址不存在"+uri);
            return;
        }

        Object object = mvcMappingInfo.getObject();
        Method method = mvcMappingInfo.getMethod();
        String invoke = null;
        try {
            invoke = (String) method.invoke(object, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ResponseType responseType = mvcMappingInfo.getResponseType();
        switch (responseType){
            case TEXT:
                assert invoke != null;
                resp.getWriter().write(invoke);
                break;
            case VIEW:
                resp.sendRedirect(invoke);
                break;
        }
    }
}
